import { PageContainer } from '@ant-design/pro-layout';
import TbaleExplainMap from '@/components/TipsMap';
import {
  EllipsisOutlined,
  PlusOutlined,
  FileSearchOutlined,
} from '@ant-design/icons';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, message, Space, Tag, Table, Select, Breadcrumb } from 'antd';
const { Option } = Select;
import React, { useEffect, useRef, useState } from 'react';
import { Link, history, Switch, useRequest } from 'umi';
import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProCard,
  ProFormInstance,
} from '@ant-design/pro-components';
import { useBoolean } from 'ahooks';
import { UpLoadTemplate } from '../commons/UpLoadTemplate';
import ReturnTablist from '@/components/TabList';
import { authAdapter2 } from '../commons/Adapter';
import ExportExcel from '@/components/ExportExcel';
import TabBarExtraButton from '../commons/TabBarExtraButton';
import moment from 'moment';

export default () => {
  const [personFlag, setPersonFlag] = useState(false);
  const [directionFlag, setDirectionFlag] = useState(false);
  const [teamFlag, setTeamFlag] = useState(false);
  const [managerFlag, setManagerFlag] = useState(false);
  const [tabKey, setTabKey] = useState('个人视角');
  const [exportUse, setExportUse] = useState('');

  const [group, setGroup] = useState({ data: [] });
  const [direction, setDirection] = useState({ data: [], group: [] });
  const [manager, setManager] = useState({
    data: [],
    group: [],
    direction: [],
  });

  const [dataSource, setDataSource] = useState([]);
  const [selectRow, { toggle }] = useBoolean(false);
  const [url, setUrl] = useState(
    'http://10.1.40.84:9998/project/getInterProjList',
  );
  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const getAllLabel = useRequest((data = null) => {
    return {
      url: 'http://10.1.40.84:9993/getAllLabel',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  const getUserInfo = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserInfo',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const getInterProjList = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9998/project/getInterProjList',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const deleteInterProj = useRequest(
    (data = null) => {
      return {
        url: `http://10.1.40.84:9998/project/deleteInterProj?id=${data}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      formatResult: (res) => res,
      manual: true,
      onSuccess: (result, param) => {
        message.info(result.msg);
      },
    },
  );

  const getListByRole: any = (role: any) => {
    switch (role) {
      case '个人视角':
        return [];
      case '子方向视角':
        return group;
      case '方向视角':
        return direction;
      case '管理员视角':
        return manager;
    }
  };

  useEffect(() => {
    getUserInfo.run().then((data) => {
      if (typeof data === 'object') {
        setGroup(data.res.ROLE_子方向负责人 || { data: [] });
        setDirection(data.res.ROLE_方向负责人 || { data: [], group: [] });
        setManager(
          data.res.ROLE_管理员 || { data: [], group: [], direction: [] },
        );
      } else {
        message.error(data);
      }
    });
    switch (ReturnTablist()[0].key) {
      case '个人视角':
        getInterProjList.run({ queryType: 'personal' }).then((data) => {
          setDataSource(data);
        });
        break;
      case '子方向视角':
        getInterProjList.run({ queryType: 'group' }).then((data) => {
          setDataSource(data);
        });
        break;
      case '方向视角':
        getInterProjList.run({ queryType: 'direction' }).then((data) => {
          setDataSource(data);
        });
        break;
      case '管理员视角':
        getInterProjList.run({ queryType: 'all' }).then((data) => {
          setDataSource(data);
        });
        break;
    }
  }, []);

  useEffect(() => {
    getInterProjList.run({ queryType: authAdapter2(tabKey) });
  }, [tabKey]);

  const columns = [
    {
      title: '序号',
      align: "center",
      key: 'seq',
      dataIndex: 'seq',
      sorter: {
        compare: (a, b) => a.seq - b.seq,
        multiple: 3,
      },
      hideInSearch: true,
      width: 60,
      hideInTable: localStorage.getItem('identity') !== '管理员',
    },
    {
      title: '项目名称',
      align: "center",
      key: 'projectName',
      dataIndex: 'projectName',
      width: 350,
      copyable: true,
    },
    {
      title: '人员',
      align: "center",
      key: 'director',
      dataIndex: 'director',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '人员',
      align: "center",
      key: 'userAccount',
      dataIndex: 'userAccount',
      hideInTable: true,
      hideInSearch: tabKey === '个人视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getListByRole(tabKey)?.data?.map((item: any) => (
              <Option key={item.value} value={item.userId}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '方向名称',
      align: "center",
      key: 'directionId',
      dataIndex: 'directionId',
      hideInTable: true,
      hideInSearch: tabKey !== '管理员视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getListByRole(tabKey)?.direction?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '子方向名称',
      align: "center",
      key: 'groupId',
      dataIndex: 'groupId',
      hideInTable: true,
      hideInSearch: tabKey === '个人视角' || tabKey === '子方向视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getListByRole(tabKey)?.group?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '合作国家/地区',
      align: "center",
      key: 'cptArea',
      dataIndex: 'cptArea',
      hideInSearch: true,
    },
    {
      title: '总经费(万元)',
      align: "center",
      dataIndex: 'totalFund',
      key: 'totalFund',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      align: "center",
      dataIndex: 'startTime',
      key: 'startTime',
      valueType: 'dateMonth',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      align: "center",
      dataIndex: 'endTime',
      key: 'endTime',
      valueType: 'dateMonth',
      hideInSearch: true,
    },
    {
      title: '标签',
      align: "center",
      dataIndex: 'labelNames',
      key: 'labelNames',
      hideInSearch: true,
      hideInTable: localStorage.getItem('identity') !== '管理员',
      width: 120,
      render: (_, record: any) => (
        <Space direction="vertical">
          {record.labelNames.map((e: any) => (
            <Tag key={e}>{e}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '标签',
      align: "center",
      dataIndex: 'labelIds',
      key: 'labelIds',
      hideInTable: true,
      hideInSearch: localStorage.getItem('identity') !== '管理员',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
            mode="multiple"
          >
            {getAllLabel?.data?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '状态',
      align: "center",
      key: 'finalStr',
      dataIndex: 'finalStr',
      hideInSearch: true,
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: {
        未提交: { text: '未提交' },
        待上传文件: {
          text: '待上传文件',
        },
        待用户修改: {
          text: '待用户修改',
        },
        待子方向负责人审核: {
          text: '待子方向负责人审核',
        },
        待子方向负责人确认: {
          text: '待子方向负责人确认',
        },
        待管理员审核: {
          text: '待管理员审核',
        },
      },
    },
    {
      title: '操作',
      align: "center",
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (_: any, record: any) => {
        let optionName: any = '';
        let singleRefuseShow: boolean = false;
        let singleRefuseDisabled: boolean = true;

        let deleteHidden: boolean = true;
        if (tabKey === '管理员视角') {
          deleteHidden = false;
        } else {
          if (
            record.finalStr === '待子方向负责人审核' ||
            record.finalStr === '未提交' ||
            record.finalStr === '待上传文件'
          ) {
            deleteHidden = false;
          }
        }

        if (tabKey === '管理员视角') {
          if (record.finalStr === '待管理员审核') {
            singleRefuseDisabled = false;
            optionName = '修改';
          } else {
            optionName = '查看';
          }
        } else {
          if (tabKey === '子方向视角') {
            if (record.finalStr === '待子方向负责人审核') {
              optionName = '修改';
              singleRefuseDisabled = false;
            } else if (record.finalStr === '待子方向负责人确认') {
              optionName = '审核';
            } else {
              optionName = '查看';
            }
          }
          if (tabKey === '方向视角') {
            optionName = '查看';
            singleRefuseShow = true;
          }
          if (tabKey === '个人视角') {
            singleRefuseShow = true;
            if (record.finalStr === '未提交') {
              optionName = '继续填写';
            } else if (
              record.finalStr === '待用户修改' ||
              record.finalStr === '待上传文件'
            ) {
              optionName = '修改';
            } else {
              optionName = '查看';
            }
          }
        }

        return (
          <Space>
            <Button
              type="link"
              key="view"
              size="small"
              onClick={() => {
                if (optionName === '修改' || optionName === '继续填写') {
                  localStorage.setItem('isEdit', '修改');
                } else if (optionName === '审核') {
                  localStorage.setItem('isEdit', '审核');
                } else {
                  localStorage.setItem('isEdit', '查看');
                }
                history.push(
                  '/LabAchievements/ScientificResearch/InterCoopProject/EditInterCoopProject/' +
                    record.id,
                );
              }}
            >
              {optionName}
            </Button>
            <Button
              type="link"
              key="agree"
              size="small"
              hidden={singleRefuseShow}
              disabled={singleRefuseDisabled}
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'INTER_CPT_PROJECT',
                    ids: [record.id],
                    status: 2, //审核通过
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    getInterProjList.run({ queryType: authAdapter2(tabKey) });
                  });
              }}
            >
              同意
            </Button>
            <ModalForm
              title="拒绝"
              trigger={
                <Button
                  type="link"
                  hidden={singleRefuseShow}
                  disabled={singleRefuseDisabled}
                  size="small"
                >
                  拒绝
                </Button>
              }
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
                destroyOnClose: true,
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                console.log(values);
                updateStatus
                  .run({
                    tableName: 'INTER_CPT_PROJECT',
                    ids: [record.id],
                    status: 3, //拒绝
                    message: values.message,
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    getInterProjList.run({ queryType: authAdapter2(tabKey) });
                  });
                return true;
              }}
              grid={true}
              initialValues={{ message: record.message }}
            >
              <ProForm.Group>
                <ProFormText
                  name="message"
                  label="拒绝原因"
                  placeholder="请输入拒绝原因"
                  colProps={{ span: 24 }}
                  rules={[{ required: true, message: '请输入拒绝原因' }]}
                />
              </ProForm.Group>
            </ModalForm>
            <Button
              type="link"
              size="small"
              disabled={deleteHidden}
              onClick={() => {
                deleteInterProj.run(record.id).then(() => {
                  getInterProjList.run({ queryType: authAdapter2(tabKey) });
                });
              }}
            >
              删除
            </Button>
          </Space>
        );
      },
      width: 140,
    },
  ];
  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>科学研究</Breadcrumb.Item>
            <Breadcrumb.Item>国际合作项目</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      tabList={ReturnTablist()}
      onTabChange={(key) => {
        setTabKey(key);
      }}
    >
      <ProTable
        style={{ marginTop: 12 }}
        // search={false}
        request={async (param: any) => {
          var tableData: any = [];
          await getInterProjList.run({
            ...param,
            queryType: authAdapter2(tabKey),
          });
          setExportUse(param);
          return { data: tableData || [], seccess: true };
        }}
        columns={columns}
        cardBordered
        search={{
          labelWidth: 'auto',
        }}
        dataSource={getInterProjList.data}
        rowKey="id"
        loading={getInterProjList.loading}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="项目列表"
        toolBarRender={() => [
          <TabBarExtraButton
            tableName={'INTER_CPT_PROJECT'}
            url={url}
            params={{ auth: authAdapter2(tabKey) }}
          />,
          <div>
            {tabKey === '管理员视角' || tabKey === '子方向视角' ? (
              <Button
                type="primary"
                icon={<FileSearchOutlined />}
                onClick={() => {
                  toggle();
                }}
              >
                批量审核
              </Button>
            ) : null}
          </div>,
          <ExportExcel
            key="ExportExcel"
            tableName={'INTER_CPT_PROJECT'}
            dataSource={getInterProjList?.data}
            queryType={authAdapter2(tabKey)}
            select={exportUse}
          />,
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              localStorage.setItem('isEdit', '修改');
              history.push(
                '/LabAchievements/ScientificResearch/InterCoopProject/EditInterCoopProject/new',
              );
            }}
          >
            新建
          </Button>,
        ]}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                getCheckboxProps: (record) => {
                  let selectRowTag: boolean = true;
                  if (tabKey === '子方向视角') {
                    if (record.finalStr === '待子方向负责人审核') {
                      selectRowTag = false;
                    }
                  }
                  if (tabKey === '管理员视角') {
                    if (record.finalStr === '待管理员审核') {
                      selectRowTag = false;
                    }
                  }
                  return { disabled: selectRowTag };
                },
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a
              style={{ marginLeft: 8 }}
              onClick={(e) => {
                onCleanSelected();
                toggle();
              }}
            >
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'INTER_CPT_PROJECT',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    getInterProjList
                      .run({ queryType: authAdapter2(tabKey) })
                      .then((data) => {
                        setDataSource(data);
                      });
                  });
              }}
            >
              {tabKey === '子方向视角' ? '提交管理员审核' : '审核通过'}
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
